package com.seata.storage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.seata.config.CommonResult;
import com.seata.storage.po.Storage;
import com.seata.storage.service.StorageService;
import io.seata.spring.annotation.GlobalLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * TODO
 *
 * @author zxx
 * @version 1.0
 * @date 2021/5/28 11:52
 */
@RestController
@RequestMapping(value = "/storage")
public class StorageController {

    @Autowired
    private StorageService storageService;

    @GlobalLock
    @PostMapping("/add")
    public CommonResult add(@RequestParam("productId") Long productId, @RequestParam("count") Integer count) {
        Storage storage = get(productId);
        if(storage == null){
            storageService.save(Storage.builder().productId(productId).total(count).build());
        }else {
            storageService.update(Storage.builder()
                    .total(storage.getTotal()+count)
                    .build()
            ,new UpdateWrapper<Storage>()
                    .lambda()
                    .eq(Storage::getId,storage.getId())
            );
        }
        return new CommonResult(get(productId),"增加库存成功！", 200);
    }
    @GlobalLock(lockRetryInternal = 500,lockRetryTimes = 30)
    @RequestMapping("/get")
    public Storage get(@RequestParam("productId") Long productId) {
        Storage storage = storageService.getOne(
                new QueryWrapper<Storage>()
                        .lambda()
                        .eq(Storage::getProductId,productId)
                .last("for update")
        );
        return storage;
    }

    /**
     * 扣减库存
     */
    @PostMapping("/decrease")
    public CommonResult decrease(
            @RequestParam("productId") Long productId
            , @RequestParam("count") Integer count
            , @RequestParam(value = "commit",required = false,defaultValue = "true") boolean commit
    ) {
        storageService.decrease(productId, count,commit);
        return new CommonResult(get(productId),"扣减库存成功！", 200);
    }
}
